package com.pansoft.openplanet.manager;


import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.login.APKUpdateControl;
import com.efounder.login.LoginByRestFul;
import com.efounder.tbs.Md5Tool;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.util.TCAccountManager;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.utilcode.util.LogUtils;
import com.utilcode.util.StringUtils;

import net.sf.json.JSONObject;

import java.util.HashMap;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

//星际通讯登录管理
public class OpenPlanetLoginManager {

    private static final String TAG = "OpenLoginWithPassword";
    private Context mContext;
    private LoginListener listener;
    //检查apk版本 默认true
    private boolean checkVerison = true;

    public OpenPlanetLoginManager(Context mContext) {
        this.mContext = mContext;
    }

    public void login(final String number, final String etPassword, String passwordType) {
        if (listener == null) {
            return;
        }
        listener.showLoginLoading(ResStringUtil.getString(R.string.common_text_islogining));
        HashMap<String, String> params = new HashMap<>();
        params.put("grant_type", "password");
        params.put("client_id", "a6f23fbb-0a1d-4e10-be7e-89181cdf089c");
        params.put("client_secret", "2a6a9640-9a46-4622-b226-bc94b852848c");
//        params.put("passwordType", "password");
        // params.put("passwordType", "smsCode");
        params.put("passwordType", passwordType);
        params.put("username", number);
        params.put("password", etPassword);
        TCRequestUtil.postCommonRequest(TAG, "oauth/accessToken", params, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                if (listener == null) {
                    return;
                }
                listener.dismissLoginloading();
                try {
                    JSONObject jsonObject = JSONObject.fromObject(response);

                    if (!jsonObject.has("access_token")) {

                        if (jsonObject.has("msg")) {
                            listener.tcLoginFail(jsonObject.getString("msg"));
                        } else {
                            listener.tcLoginFail(ResStringUtil.getString(R.string.common_text_login_fail));
                            LogUtils.e("请求access_token失败，登录失败");
                        }
                        return;
                    }


                    //登录成功后将token保存在EV中
                    EnvironmentVariable.setProperty("tc_access_token", jsonObject.getString("access_token"));
                    EnvironmentVariable.setProperty("tc_refresh_token", jsonObject.getString("refresh_token"));

                    if (!jsonObject.has("userInfo")) {
//                        listener.tcLoginFail("登录失败,获取用户信息失败");
                        listener.tcLoginFail(ResStringUtil.getString(R.string.common_text_login_fail));

                        return;
                    }

                    JSONObject user = jsonObject.getJSONObject("userInfo");
                    EnvironmentVariable.setProperty("tc_user_info", user.toString());

                    String ethAddress = user.optString("ethAddress", "");
                    if (!ethAddress.toLowerCase().startsWith("0x") && !ethAddress.equals("")) {
                        ethAddress = "0x" + ethAddress;
                    }
                    EnvironmentVariable.setProperty("tc_ethAddress", ethAddress);
//                    EnvironmentVariable.setProperty("tc_ethPublicKey", user.optString("ethPublicKey", ""));
                    //todo 兼容ios
                    EnvironmentVariable.setProperty("tc_ethPublicKey", TCAccountManager.convertTo10Radix(user.optString("ethPublicKey", "")));

                    EnvironmentVariable.setProperty("tc_planet", user.optString("planet", ""));
                    //保存用户 rsa 工钥

                    EnvironmentVariable.setUserID(String.valueOf(user.getInt("imUserId")));
                    EnvironmentVariable.setProperty(CHAT_USER_ID, String.valueOf(user.getInt("imUserId")));
                    EnvironmentVariable.setProperty(CHAT_PASSWORD, user.getString("imPassword"));
                    //EnvironmentVariable.setProperty(RSAUtil.getCurrentPublicKey(), user.optString("comPublicKey", null));
                    EnvironmentVariable.setUserName(String.valueOf(number));
                    EnvironmentVariable.setPassword(Md5Tool.hashKey(etPassword));

                    //不检查版本更新，直接返回
                    if (checkVerison == false) {
                        listener.tcLoginSuccess();
                        return;
                    }

//                    String path = Constant.UNZIP_DIR + "/" + EnvironmentVariable.getProperty("res_version");
//                    File versionFile = new File(path);
//                    if (!versionFile.exists()) {
//                        listener.showLoginLoading(ResStringUtil.getString(R.string.common_text_isunziping));
//                        CommonThreadPoolUtils.execute(new Runnable() {
//                            @Override
//                            public void run() {
//                                try {
//                                    ResFileManager.unZipAssetsToSD(mContext, "res.zip",
//                                            Environment.getExternalStorageDirectory()
//                                                    .getAbsolutePath()
//                                                    + File.separator + appSdcardBaseLocation, true);
//                                    ((Activity) mContext).runOnUiThread(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            listener.dismissLoginloading();
//                                            //listener.tcLoginSuccess();
//                                            // checkApkVersion();
//                                            checkUserRSAInfo();
//                                        }
//                                    });
//
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                        });
//
//                    } else {
//                        // listener.tcLoginSuccess();
//                        checkUserRSAInfo();
//                        //checkApkVersion();
//
//                    }
                    checkUserRSAInfo();


                } catch (Exception e) {
                    e.printStackTrace();
                    if (listener != null) {
                        // listener.dismissLoginloading();
                        listener.tcLoginFail(ResStringUtil.getString(R.string.common_text_login_fail));
                    }

                }
            }

            @Override
            public void onFail(String error) {
                if (listener != null) {
                    listener.dismissLoginloading();
                    if ("TokenExpireLogOut".equals(error)) {
                        listener.tcLoginFail(ResStringUtil.getString(R.string.username_or_password_wrong));
                        return;
                    }
                    listener.tcLoginFail(ResStringUtil.getString(R.string.common_text_login_fail));
                }

            }
        });


    }


    //检查用户rsa 密钥信息
    private void checkUserRSAInfo() {
//        CompatibleOldVersionUtil.checkLocalInfoIsFull(mContext, new CompatibleOldVersionUtil.CheckListener() {
//            @Override
//            public void checkSuccess() {
//                checkApkVersion();
//            }
//
//            @Override
//            public void checkFail() {
//                ToastUtil.showToast(mContext, "获取RAS密钥失败，请重试！");
//            }
//        });
        if (EnvSupportManager.isSupportGooglePlayUpgrade()) {
            //支持谷歌的应用只需要检查资源文件版本号
            APKUpdateControl apkUpdateControl = new APKUpdateControl();
            apkUpdateControl.CheckRESVerion(mContext, null, msgHandler);
        } else {
            checkApkVersion();
        }
    }

    private MsgHandler msgHandler = new MsgHandler();

    class MsgHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                case 2:
                    listener.tcLoginSuccess();
                    break;
            }
        }
    }

    //检查apk版本号
    public void checkApkVersion() {
        LoadingDataUtilBlack.show(mContext, ResStringUtil.getString(R.string.common_text_islogining));

        LoginByRestFul loginByRestFul = new LoginByRestFul(1);
        loginByRestFul.setOpenPlanetLoginListener(new LoginByRestFul.OpenPlanetLoginListener() {

            @Override
            public void loginSuccess(String response) {
                listener.tcLoginSuccess();
            }

            @Override
            public void loginFail(String fail) {

                EnvironmentVariable.setProperty("tc_ethAddress", "");
                EnvironmentVariable.setProperty("tc_ethPublicKey", "");
                EnvironmentVariable.setProperty("tc_planet", "");
                EnvironmentVariable.setUserID("");
                EnvironmentVariable.setProperty(CHAT_USER_ID, "");
                EnvironmentVariable.setProperty(CHAT_PASSWORD, "");

                listener.tcLoginFail(ResStringUtil.getString(R.string.common_text_chcek_version_fail));
            }
        });
        // TCLoadingDataView.show(mContext, "请稍候");
        loginByRestFul.loginBegin(mContext, "", "");
    }

    public void setLoginListener(LoginListener loginListener) {
        this.listener = loginListener;
    }

    /**
     * 设置是否检查更新
     *
     * @param isCheckVersion
     */
    public void setCheckApkVersion(boolean isCheckVersion) {
        this.checkVerison = isCheckVersion;
    }

    public interface LoginListener {
        void tcLoginSuccess();

        void showLoginLoading(String msg);

        void dismissLoginloading();

        void tcLoginFail(String error);
    }
}

